import React, { useEffect, useState } from "react"
import { flushSync } from "react-dom"
import { } from "react-router-dom";
import './Login.less';
import {
    Form,
    Input,
    Button,
    Dialog,
    Toast
} from 'antd-mobile'

import { connect } from "react-redux";

import action from "@/store/action"

import ViewHeader from 'Co/ViewHeader'
const Login = function (props) {
    const { navigate, LOGIN_POST, REGISTER_POST, ups } = props
    const [form] = Form.useForm()
    let [isResigter, setIsResigter] = useState(false);
    let [dd, ddd] = useState(false);
   
    const onFinish = async (values) => {
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })
        try {
            let res = isResigter ? await REGISTER_POST(values) : await LOGIN_POST(values);
            if (res.code == -200) {
                Toast.show({
                    icon: 'fail',
                    content: res.msg,
                    duration: 3000
                })
            } else {
                Toast.show({
                    icon: 'success',
                    content: res.msg,
                    duration: 3000
                })
                setTimeout(() => {
                    let to = ups.get('to')
                    ups.delete('to')
                    if (to) {
                        navigate(`${to}?${ups.toString()}`, {
                            replace: true
                        })
                    } else {
                        navigate({
                            pathname: '/'
                        })
                    }

                }, 2000)
            }
        } catch (error) {
            console.error(error);

        }

    }


    const checkUseName = (_, value) => {
        if (/^[A-Za-z][A-Za-z0-9]{5,}/.test(value.trim())) {
            return Promise.resolve()
        }
        return Promise.reject(new Error('用户名字母开头且至少6位字符'))
    }

    const checkMobile = (_, value) => {
        const passwordConfirm = form.getFieldValue('passwordConfirm')
        if (/[0-9]{6,12}$/.test(value.trim())) {
            if (passwordConfirm && value.trim() !== passwordConfirm) {
                return Promise.reject(new Error('2次密码不同!'))
            }
            return Promise.resolve()
        }
        return Promise.reject(new Error('密码不正确!'))
    }

    const passwordConfirm = (_, value) => {
        const password = form.getFieldValue('password')
        if (/[0-9]{6,12}$/.test(value.trim())) {
            if (/[0-9]{6,12}$/.test(value.trim())) {
                if (password.trim() && value.trim() !== password.trim()) {
                    return Promise.reject(new Error('2次密码不同!'))
                }
                return Promise.resolve()
            }
            return Promise.reject(new Error('二次密码不正确!'))
        }
    }



    return (
        <>
            <div className="login-box">
                <ViewHeader title="登录/注册" navigate ={navigate}/>
                <div className="login-box-title">默认账号:feichong124 密码:123456</div>
                <Form
                    form={form}
                    onFinish={onFinish}
                    style={{
                        '--border-top': 'none',
                        '--border-inner': 'none',
                        '--border-bottom': 'none',
                    }}
                    layout='horizontal'
                    footer={
                        <div style={{ display: 'flex', justifyContent: "space-around" }}>
                            <Button block style={{ flex: '0 1 33%' }} type='submit' color='primary' size='large'>
                                提交
                            </Button>

                            <Button block style={{ flex: '0 1 33%' }} type='button' color='primary' size='large' onClick={() => { setIsResigter(!isResigter ? true : false) }}>
                                {!isResigter ? '切换注册' : '切换登录'}
                            </Button>
                        </div>
                    }
                    initialValues={{
                        username: '',
                        password: '',
                        passwordConfirm: ''
                    }}
                >
                    <Form.Item label='用户名' name='username' validateTrigger='onBlur'
                        rules={[{ validator: checkUseName }]}>
                        <Input placeholder='请输入用户名' clearable />
                    </Form.Item>
                    <Form.Item label='密码' name='password' dependencies={['passwordConfirm']} validateTrigger={['onBlur']}
                        rules={[{ validator: checkMobile }]}
                    >
                        <Input placeholder='请输入密码' clearable type='password' />
                    </Form.Item>
                    {isResigter ? < Form.Item label='确认密码' name='passwordConfirm' dependencies={['password']} validateTrigger={['onBlur']}
                        rules={[{ validator: passwordConfirm }]}
                    >
                        <Input placeholder='请输入确认密码' clearable type='password' />
                    </Form.Item> : <></>
                    }
                </Form>

            </div>;
        </>
    )

}

export default connect(null, action.login)(Login)

